const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  
  if (!openid) {
    return {
      isLogin: false,
      message: '获取用户信息失败'
    };
  }
  
  try {
    // 查询用户信息
    const userResult = await db.collection('users').doc(openid).get();
    
    if (userResult.data) {
      return {
        isLogin: true,
        userInfo: {
          _id: openid,
          ...userResult.data
        }
      };
    } else {
      return {
        isLogin: false,
        message: '用户未注册'
      };
    }
  } catch (error) {
    console.error('检查登录状态出错:', error);
    return {
      isLogin: false,
      message: '检查登录状态失败',
      error: error.message
    };
  }
};